import * as api from '@/api/crud';
import { getToken, removeToken, setToken } from '@/utils/auth';

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    user: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_USER(state, user) {
      state.user = user;
    }
  },

  actions: {
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        api.request({
          path: 'user/login',
          data: userInfo
        }).then(({ data }) => {
          commit('SET_TOKEN', data.token);
          setToken(data.token);
          resolve();
        }).catch((error) => {
          reject(error);
        });
      });
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        api.request({
          path: 'user/info',
          data: {
            token: state.token
          },
          method: 'GET'
        })
          .then(({ data }) => {
            if (!data) {
              reject('登录失败，请稍后重试');
            }
            if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', data.roles);
            } else {
              reject('【获取用户信息失败】用户权限必须是一个数组！');
            }
            commit('SET_NAME', data.name);
            commit('SET_AVATAR', data.avatar);
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        api.request({
          path: 'user/logout',
          method: 'GET'
        })
          .then(() => {
            commit('SET_TOKEN', '');
            commit('SET_ROLES', []);
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        removeToken();
        resolve();
      });
    }
  }
};

export default user;
